package com.hyg.lib_base.mainUtils;

import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.recyclerview.widget.LinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;

/**
 * @description: 蓝牙方法工具类
 * @author: ODM
 * @date: 2020/4/13
 */
public class BluetoothUtils {
    Context context;
    BluetoothAdapter mBluetoothAdapter;
    ArrayList<String> list = new ArrayList<>();
    ArrayList<BluetoothDevice> arrayList = new ArrayList<>();
    ArrayList<BluetoothDevice> arrayList1 = new ArrayList<>();
    private String pin = "0000";
    BluetootnStateChangeListener listener;

    public BluetoothUtils(Context context) {
        this.context = context;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        regiseBluetoothReceiver();
    }


    /**
     * 获取已连接的蓝牙设备的电量
     */
    public static void getBluetoothDeviceBattery() {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        //获取BluetoothAdapter的Class对象
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;
        try {
            //反射获取蓝牙连接状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开使用这个方法的权限
            method.setAccessible(true);
            int state = (int) method.invoke(btAdapter, (Object[]) null);

            if (state == BluetoothAdapter.STATE_CONNECTED) {
                //获取在系统蓝牙的配对列表中的设备--！已连接设备包含在其中
                Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
                for (BluetoothDevice device : devices) {
                    Method batteryMethod = BluetoothDevice.class.getDeclaredMethod("getBatteryLevel", (Class[]) null);
                    batteryMethod.setAccessible(true);
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    isConnectedMethod.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    int level = (int) batteryMethod.invoke(device, (Object[]) null);
                    if (device != null && level > 0 && isConnected) {
                        String deviceName = device.getName();
                        Log.i("lgb", "getBluetoothDeviceBattery: " + deviceName + "    电量:  " + level);
                    }
                }
            } else {
                ToastUtils.showLong("No Connected Bluetooth Devices Found");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public boolean getBluetoothIsOpen() {
        return mBluetoothAdapter.isEnabled();
    }

    public boolean getBluetoothEnable() {
        return mBluetoothAdapter != null;
    }

    public Set<BluetoothDevice> getpairedDevices() {
        if (getBluetoothIsOpen()) {
            return mBluetoothAdapter.getBondedDevices();
        } else {
            return null;
        }
    }

    public void setStateChangeListener(BluetootnStateChangeListener listener) {
        this.listener = listener;
    }

    public void startSearchBluetoothDevice() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            return;
        }
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        boolean result = mBluetoothAdapter.startDiscovery();
    }

    public void stopRefresh() {
        if (mBluetoothAdapter == null) {
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            return;
        }
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
    }


    public void regiseBluetoothReceiver() {
        // 注册这个 BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        IntentFilter filter1 = new IntentFilter(android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        IntentFilter filter2 = new IntentFilter(android.bluetooth.BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        IntentFilter filter4 = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
        IntentFilter filter5 = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        IntentFilter filter6 = new IntentFilter(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
        IntentFilter filter7 = new IntentFilter("android.bluetooth.headset.profile.action.ACTIVE_DEVICE_CHANGED");
        IntentFilter filter8 = new IntentFilter("android.bluetooth.a2dp.profile.action.ACTIVE_DEVICE_CHANGED");
        context.registerReceiver(mReceiver, filter);
        context.registerReceiver(mReceiver, filter1);
        context.registerReceiver(mReceiver, filter2);
        context.registerReceiver(mReceiver, filter4);
        context.registerReceiver(mReceiver, filter5);
        context.registerReceiver(mReceiver, filter6);
        context.registerReceiver(mReceiver, filter7);
        context.registerReceiver(mReceiver, filter8);
    }


    // 创建一个接受 ACTION_FOUND 的 BroadcastReceiver
    private  BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (!TextUtils.isEmpty(device.getName())) {
                    if (listener != null) listener.onProgress(device);
                    Log.i("lgb", "onReceive: 扫描中");
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                Log.i("lgb", "onReceive: 开始扫描");
                if (listener != null) listener.onStart();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Log.i("lgb", "onReceive: 结束扫描");
                if (listener != null) listener.onFinish();

            } else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
                Log.i("lgb", "onReceive action=: " + action);

            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                Log.i("lgb", "onReceive:ACTION_BOND_STATE_CHANGED ");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_NONE:
                        Log.d("lgb", "取消配对");
                        if (listener != null) listener.onBindingCancel(device);
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Log.d("lgb", "配对中");
                        if (listener != null) listener.onBinding(device);
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Log.d("lgb", "配对成功");
//                        if (listener != null) listener.onBinding(device);
                        break;
                }
            } else if (BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                Log.i("lgb", "onReceive:ACTION_CONNECTION_STATE_CHANGED ========" + action);
                switch (intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1)) {
                    case BluetoothA2dp.STATE_CONNECTING:
                        BluetoothDevice device111 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        if (listener != null) listener.onConnecting(device111);
                        break;
                    case BluetoothA2dp.STATE_CONNECTED:
                        device111 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        Log.i("lgb", "onReceive:onConnected ");
                        if (listener != null) listener.onConnected(device111);
                        break;
                    case BluetoothA2dp.STATE_DISCONNECTING:
                        device111 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        Log.i("lgb", "onReceive: device: " + device111.getName() + " disconnecting");
                        break;
                    case BluetoothA2dp.STATE_DISCONNECTED:
                        device111 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        Log.i("lgb", "onReceive: device: " + device111.getName() + " disconnected");
                        break;
                    default:
                        break;
                }
            } else if ("android.bluetooth.headset.profile.action.ACTIVE_DEVICE_CHANGED".equalsIgnoreCase(action)) {
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    BluetoothDevice device = bundle.getParcelable(BluetoothDevice.EXTRA_DEVICE);
                    if (listener != null) listener.onHeadsetActiveChanged(device);
                }
            } else if ("android.bluetooth.a2dp.profile.action.ACTIVE_DEVICE_CHANGED".equalsIgnoreCase(action)) {
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    BluetoothDevice device = bundle.getParcelable(BluetoothDevice.EXTRA_DEVICE);
                    if (listener != null) listener.onA2dpActiveChanged(device);
                }
            }
        }
    };


    public void onDestroy() {
        stopRefresh();
        if (mReceiver != null) {
            context.unregisterReceiver(mReceiver);
            mReceiver=null;
        }
    }


    public interface BluetootnStateChangeListener {
        void onStart();

        void onCancel();

        void onFinish();

        void onProgress(BluetoothDevice device);

        void onConnecting(BluetoothDevice device);

        void onBinding(BluetoothDevice device);

        void onBindingCancel(BluetoothDevice device);

        void onConnected(BluetoothDevice device);

        void onHeadsetActiveChanged(BluetoothDevice device);

        void onA2dpActiveChanged(BluetoothDevice device);

    }

    public static boolean isMusicProduct(BluetoothDevice device) {
        return device.getName().contains("MT-YM") || device.getName().contains("MT-YC");
//        return true;
    }


}
